package com.talent.web.config.security;

import com.talent.web.model.entity.TlUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.talent.web.utils.TlConstant.AUTHORITIES;
import static com.talent.web.utils.TlConstant.TALENT;

/**
 * @ClassName：JwtProvider
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: jwt生成解析
 */
@Component
@RequiredArgsConstructor
public class JwtProvider {


    private final AuthProperties authProperties;

    public String generateToken(TalentUserDetails userDetails) {
        return Jwts.builder().setSubject(userDetails.getUsername())
                .setId(userDetails.getId().toString())
                .claim(AUTHORITIES,userDetails.getAuthorities())
                .setIssuer(TALENT)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + authProperties.getExpire()))
                .signWith(SignatureAlgorithm.HS256,authProperties.getSecret()).compact();
    }

    public String generateToken(TlUser user) {
        return Jwts.builder().setSubject(user.getUsername())
                .setId(user.getId().toString())
                .claim(AUTHORITIES,new ArrayList<>())
                .setIssuer(TALENT)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + authProperties.getExpire()))
                .signWith(SignatureAlgorithm.HS256,authProperties.getSecret()).compact();
    }


    public TalentUserDetails parseToken(String token){
        Claims body = Jwts.parser().setSigningKey(authProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
        body.getExpiration().before(new Date());
        TalentUserDetails userDetails = new TalentUserDetails();
        userDetails.setUsername(body.getSubject());
        userDetails.setId(Long.parseLong(body.getId()));
        Object authoritiesObj = body.get(AUTHORITIES);
        List<String> authorities =new ArrayList<>();
        if(authoritiesObj instanceof List){
            for(Object object : (List) authoritiesObj){
                authorities.add((String)((Map) object).get("authority"));
            }
        }
           userDetails.setAuthorities(authorities);
        return userDetails;
    }


}
